package com.java.IO.file_stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileInputStreamAPI {
    // 读取所有文件类型的文件内的所有内容
    public static List<Byte> readAllContentsOfFile(String path) throws Exception {
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            List<Byte> resultBytes = new ArrayList();
            
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = fileInputStream.read(buffer)) != -1) {
                Byte[] bytes = new Byte[length];
                for (int i = 0; i < length; i++) {
                    bytes[i] = buffer[i];
                }
                
                resultBytes = Stream.concat(resultBytes.stream(), Arrays.stream(bytes)).collect(Collectors.toList());
            }
            return resultBytes;
        } catch (FileNotFoundException e) {
            throw new Exception("路径错误，请检查路径是否存在或正确。错误信息为" + e.getMessage());
        }
    }
    
    public static void main(String[] args) throws Exception {
        String path = "File和IO流\\com\\java\\files\\byte_stream.txt";
        
        // 创建对象：若父级路径不存在或文件不存在则抛出异常FileNotFoundException
        FileInputStream fileInputStream1 = new FileInputStream(path);
        FileInputStream fileInputStream2 = new FileInputStream(new File(path));
        
        // read：读取本地文件内数据，若无参数则一次读取一字节，若无数据则返回-1。若参数为字节数组且有数据则一次性读取字节数组长度的字节并存于该字节数组内同时返回读取到的字节长度
        System.out.println(fileInputStream1.read()); // 97
        System.out.println(fileInputStream1.read()); // 57
        System.out.println(fileInputStream1.read()); // 45
        byte[] bytes = new byte[10];
        System.out.println(fileInputStream1.read(bytes, 5, 2)); // 2
        System.out.println(Arrays.toString(bytes)); // [0, 0, 0, 0, 0, 13, 10, 0, 0, 0] (读取2个数据到数组指定位置5)
        System.out.println(fileInputStream1.read(bytes)); // 6
        System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100, 100, 101, 10, 0, 0, 0] (残留数据10)
        System.out.println(fileInputStream1.read(bytes)); // -1
        System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100, 100, 101, 10, 0, 0, 0] (全都是残留数据)
        System.out.println(fileInputStream1.read()); // -1
        
        // close：关闭流并释放资源
        fileInputStream1.close();
        fileInputStream2.close();
        
        // 读取文件内的所有内容，路径必须为文件路径
        System.out.println(readAllContentsOfFile(path)); // [97, 57, 45, 13, 10, 97, 98, 99, 100, 100, 101]
    }
}
